﻿

using Furion.DependencyInjection;

namespace Admin.NET.Application.Service;

/// <summary>
/// 系统用户
/// </summary>
public class SysUserService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<SysUser> _rep;
    private readonly SysCacheService _sysCacheService;
    private readonly SysMenuService _sysMenuService;

    public SysUserService(SqlSugarRepository<SysUser> rep, SysCacheService sysCacheService, SysMenuService sysMenuService)
    {
        _rep = rep;
        _sysCacheService = sysCacheService;
        _sysMenuService = sysMenuService;
    }

    /// <summary>
    /// 获取所有用户, 用于前端缓存
    /// </summary>
    public async Task<List<SysUserAllOutput>> All()
    {
        // TODO 不能只缓存当前租户的用户，否则会导致切换租户时用户信息不更新
        List<SysUserAllOutput> cacheData = null;  // _sysCacheService.Get<List<SysUserAllOutput>>(CacheConst.KeyUserList);
        if (cacheData == null || cacheData.Count() <= 0)
        {
            // TODO 不能只缓存当前租户的用户，否则会导致切换租户时用户信息不更新
            var userList = await _rep.Queryable
               .LeftJoin<SysOrg>((it, org) => it.OrgId == org.Id)
               .OrderBy(it => new { it.OrderNo })
               .Select<SysUserAllOutput>()
               .ToListAsync();

            cacheData = userList;
            _sysCacheService.Set(CacheConst.KeyUserList, cacheData);
        }

        return cacheData;
    }
    /// <summary>
    /// 获取指定用户的信息 🔖
    /// </summary>
    /// <param name="userId"></param>
    /// <returns></returns>
    public async Task<UserInfoOutput> GetUserInfoById(long userId)
    {
        var user = await _rep.GetFirstAsync(t => t.Id == userId) ?? throw Oops.Oh(ErrorCodeEnum.D0009);
        // 获取机构
        var org = await _rep.ChangeRepository<SqlSugarRepository<SysOrg>>().GetFirstAsync(t => t.Id == user.OrgId);
        // 获取职位
        var pos = await _rep.ChangeRepository<SqlSugarRepository<SysRole>>().GetFirstAsync(t => t.Id == user.PosId);
        // 获取按钮权限集合
        var buttons = await _sysMenuService.GetUserBtnPermList(user.Id);
        // 获取角色集合
        var roleIds = await _rep.ChangeRepository<SqlSugarRepository<SysUserRole>>().Queryable.Where(t => t.UserId == user.Id).Select(t => t.RoleId).ToListAsync();
        // 获取其他附属机构
        var extOrgIds = await _rep.ChangeRepository<SqlSugarRepository<SysUserExtOrg>>().Queryable.Where(t => t.UserId == user.Id).Select(t => t.OrgId).ToListAsync();

        return new UserInfoOutput
        {
            TenantId = user.TenantId,
            Id = user.Id,
            Account = user.Account,
            RealName = user.RealName,
            Phone = user.Phone,
            IdCardNum = user.IdCardNum,
            Email = user.Email,
            AccountType = user.AccountType,
            Avatar = user.Avatar,
            Address = user.Address,
            Signature = user.Signature,
            OrgId = user.OrgId,
            OrgName = org?.Name,
            OrgType = org?.Type,
            PosName = pos?.Name,
            Buttons = buttons,
            RoleIds = roleIds,
            ExtOrgIds = extOrgIds,
        };
    }
}